package com.sql.handler;

import java.sql.Connection;
import java.sql.SQLException;

import com.sql.handler.util.ArrayItem;
import com.sql.handler.util.Arrays;


public class ManyConnectionHandler {
	
	private static Arrays<Connection, Long> arrays;
	public static boolean isOpen = false;
	
	public ManyConnectionHandler(){
		
	}
	
	private Arrays<Connection, Long> getArrays(){
		if(arrays != null){
			return arrays;
		}
		synchronized (ManyConnectionHandler.class) {
			if(arrays == null){
				arrays = new Arrays<>();
			}
		}
		return arrays;
	}
	
	private Long getTimeMillis(){
		return System.currentTimeMillis();
	}
	
	protected void remove(Connection conn){	
		try {
			if(isOkConnection(conn)){
				getArrays().remove(conn);
			}
		} catch (SQLException e) {
		}
	}
	
	protected void add(Connection conn){
		if(conn == null){
			return;
		}
		getArrays().add(conn,getTimeMillis());
	}
	
	protected Connection getConnection() throws SQLException{
		checkArrays();
		/*得到时间最长的连接*/
		Connection conn = getLongConnection();
		if(isOkConnection(conn)){
			arrays.remove(conn);
			arrays.add(conn, getTimeMillis());
			return conn;
		}
		return null;
	}
	
	@SuppressWarnings("unused")
	private Connection getLongConnection(){
		long maxLongTime = getTimeMillis();
		Connection conn = null;
		for(int i = 0;i < arrays.size();i++){
			ArrayItem<Connection, Long> arrayItem = arrays.get(i);
			long time = arrayItem.getT2();
			if(time < maxLongTime){
				maxLongTime = time;
				conn = arrayItem.getT1();
			}
		}
		return (getTimeMillis() - maxLongTime < 5000) ? null : conn;
	}
	
	protected void checkArrays() throws SQLException{
		
		for(int i = 0;i < arrays.size();i++){
			Connection conn = arrays.get(i).getT1();
			if(!isOkConnection(conn)){
				arrays.remove(i);
			}
		}
	}
	
	private boolean isOkConnection(Connection con) throws SQLException{
    	return (con == null || con.isClosed() || !con.isValid(0)) ? false : true;
    }
}
